window.onload = function () {
    //模拟配置
    const config = {
        itemsPerPage: 10,
        maxPages: 5,
        loadingDelay: 800
    };


    const content = document.getElementById('content');
    const loadingIndicator = document.getElementById('loading');
    const sentinel = document.getElementById('sentinel');


    let currentPage = 0;
    let totalItems = 0;
    let isLoading = false;
    let hasMore = true;

    //初始化Intersection Observer
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting && hasMore && !isLoading) {
                loadMore();
            }
        });
    }, {
        root: null,
        rootMargin: '100px',
        threshold: 0.1
    });

    //注册视口dom
    observer.observe(sentinel);

    //模拟获取数据
    function fetchData() {
        return new Promise((resolve) => {
            setTimeout(() => {
                const data = [];
                for (let i = 0; i < config.itemsPerPage; i++) {
                    data.push({
                        id: totalItems + i + 1,
                        title: `项目 ${totalItems + i + 1}`,
                        content: `这是第 ${currentPage + 1} 页的第 ${i + 1} 个项目`
                    });
                }
                resolve(data);
            }, config.loadingDelay);
        });
    }

    async function loadMore() {
        if (!hasMore || isLoading) return;

        isLoading = true;
        currentPage++;
        loadingIndicator.style.display = 'block';

        try {
            const data = await fetchData();

            if (data.length === 0) {
                hasMore = false;
                loadingIndicator.textContent = '没有更多内容了';
                return;
            }

            // 渲染新项目
            data.forEach(item => {
                const itemElement = document.createElement('div');
                itemElement.className = 'item';
                itemElement.innerHTML = `
                    <h3>${item.title}</h3>
                    <p>${item.content}</p>
                    <small>ID: ${item.id}</small>
                `;
                content.insertBefore(itemElement, sentinel);
            });

            totalItems += data.length;

            // 模拟数据结束条件
            if (currentPage >= config.maxPages) {
                hasMore = false;
                loadingIndicator.textContent = '已加载全部内容';
            }
        } catch (error) {
            console.error('加载失败:', error);
            loadingIndicator.textContent = '加载失败，点击重试';
            loadingIndicator.onclick = loadMore;
            currentPage--; // 失败时回退页码
        } finally {
            isLoading = false;
            if (hasMore) {
                loadingIndicator.style.display = 'none';
            }
        }
    }

}